import requests
import json

# response = requests.get('https://httpbin.org/get')
# response = requests.get('http://127.0.0.1:4523/m2/7370634-7102517-default/373242812?apifoxApiId=373242812')
# print(response.json())
# print(response.text())
# print(dir(response))
# print(json.dumps(response.json(), indent=4))


# from urllib import request, parse
#
# # Base URL being accessed
# url = 'https://httpbin.org/get'
#
# # Dictionary of query parameters (if any)
# parms = {
#     'name1': 'value1',
#     'name2': 'value2'
# }
#
# # Encode the query string
# querystring = parse.urlencode(parms)
# print(url + '?' + querystring)
# # Make a GET request and read the response
# u = request.urlopen(url + '?' + querystring)
# # print(u.code)
# resp = u.read()
# print(resp.decode('utf-8', errors='ignore'))

# url = 'https://httpbin.org/post'
#
# # Dictionary of query parameters (if any)
# parms = {
#     'name1': 'value1',
#     'name2': 'value2'
# }
#
# # Extra headers
# headers = {
#     'User-agent': 'none/of_your_business',
#     'Spam': 'Eggs'
# }
#
# resp = requests.post(url, data=parms, headers=headers)
#
# # Decoded text returned by the request
# print(resp.text)

# resp = requests.head('http://www.python.org/index.html')
#
# status = resp.status_code
# last_modified = resp.headers['last-modified']
# content_type = resp.headers['content-type']
# content_length = resp.headers['content-length']
#
# print(status)
# print(last_modified)
# print(content_type)
#
# resp = requests.get('http://pypi.python.org/pypi?:action=login',
#                     auth=('user', 'password'))
# url = 'http://httpbin.org/post'
# files = { 'file': ('data.csv', open('data.csv', 'rb')) }
#
# r = requests.post(url, files=files)

# from socketserver import BaseRequestHandler, TCPServer
#
#
from socketserver import StreamRequestHandler, TCPServer, BaseRequestHandler
#

# class EchoHandler(BaseRequestHandler):
#     def handle(self):
#         print('Got connection from', self.client_address)
#         while True:
#
#             msg = self.request.recv(8192)
#             if not msg:
#                 break
#             self.request.send(msg)


#
# if __name__ == '__main__':
#     serv = TCPServer(('', 20000), EchoHandler)
#     serv.serve_forever()

# class EchoHandler(StreamRequestHandler):
#     def handle(self):
#         print('Got connection from', self.client_address)
#         # self.rfile is a file-like object for reading
#         for line in self.rfile:
#             # self.wfile is a file-like object for writing
#             self.wfile.write(line)


# if __name__ == '__main__':
#     serv = TCPServer(('', 20000), EchoHandler)
#     serv.serve_forever()


# import requests
# import json
#
# # response = requests.get('https://httpbin.org/get')
# response = requests.get('http://127.0.0.1:4523/m2/7370634-7102517-default/373242812?apifoxApiId=373242812')
# # print(response.json())
# # print(response.text())
# # print(dir(response))
# print(json.dumps(response.json(), indent=4))


from http.server import HTTPServer, BaseHTTPRequestHandler
import json
import urllib.parse


class CustomHTTPHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        # 解析URL路径和查询参数
        parsed_path = urllib.parse.urlparse(self.path)
        query_params = urllib.parse.parse_qs(parsed_path.query)

        # 根据路径返回不同响应
        if parsed_path.path == '/':
            self.send_response(200)
            self.send_header('Content-type', 'text/html')
            self.end_headers()
            self.wfile.write(b"<h1>Welcome to My HTTP Server</h1>")
        elif parsed_path.path == '/api/data':
            self.send_response(200)
            self.send_header('Content-type', 'application/json')
            self.end_headers()
            data = {'message': 'Hello from API', 'params': query_params}
            self.wfile.write(json.dumps(data).encode())
        else:
            self.send_response(404)
            self.send_header('Content-type', 'text/html')
            self.end_headers()
            self.wfile.write(b"404 Not Found")

    def do_POST(self):
        content_length = int(self.headers['Content-Length'])
        post_data = self.rfile.read(content_length)

        self.send_response(200)
        self.send_header('Content-type', 'application/json')
        self.end_headers()

        try:
            # 尝试解析JSON数据
            json_data = json.loads(post_data.decode('utf-8'))
            response = {'status': 'success', 'received': json_data}
        except json.JSONDecodeError:
            response = {'status': 'error', 'message': 'Invalid JSON'}

        self.wfile.write(json.dumps(response).encode())


if __name__ == '__main__':
    server = HTTPServer(('localhost', 8000), CustomHTTPHandler)
    print("自定义HTTP服务器启动在 http://localhost:8000")
    server.serve_forever()
